package lion.crawl.rule;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import lion.dev.lang.MapJ;

/**
 * @author Helin
 * @date 2012-8-19
 * @email hl_0074@sina.com
 * @desc 选择器匹配
 */
public class JsoupRule implements ParseRule {

	private MapJ selectors;
	private static Pattern pattern = Pattern.compile("\\((.*?)\\)\\@\\[(.*?)\\]");

	public JsoupRule(MapJ selectors) {

		this.selectors = selectors;
	}

	@Override
	public void extract(String content, MapJ result) {

		Document doc = Jsoup.parse(content);

		for (String key : this.selectors.keySet()) {

			String cssselecter = this.selectors.getString(key);
			String attr = null;

			Matcher matcher = pattern.matcher(cssselecter);
			if (matcher.find()) {
				cssselecter = matcher.group(1);
				attr = matcher.group(2);
			}

			System.out.println("selector:" + cssselecter + "  attr" + attr);

			Elements elements = doc.select(cssselecter);
			if (elements.isEmpty()) {
				continue;
			}
			if (StringUtils.isBlank(attr)) {
				result.put(key, elements.html());
			} else {
				result.put(key, elements.attr(attr));
			}
		}
	}

	public static void main(String[] args) {

		String string = "(.photo-img a)@[href]";
		Pattern pattern = Pattern.compile("\\((.*?)\\)\\@\\[(.*?)\\]");

		Matcher matcher = pattern.matcher(string);
		if (matcher.find()) {
			System.out.println(matcher.group(1));
			System.out.println(matcher.group(2));
		}

	}
}
